﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace BootyBay.Repository
{
    public static class QueryExtension
    {
        public static IQueryable<TResult> Filter<TResult, TKey>(this IQueryable<TResult> source,
            System.Linq.Expressions.Expression<Func<TResult, bool>> selector, TKey fiterCondition) where TResult : class
        {
            if (fiterCondition is string)
            {
                if (String.IsNullOrEmpty(fiterCondition as string))
                    return source;
            }
            else if (Equals(fiterCondition, default(TKey)))
            {
                return source;
            }

            source = source.Where(selector);
            return source;
        }

        public static void CascadingDeleteOnSubmit(this System.Data.Linq.DataContext context, object entity)
        {
            var entityType = entity.GetType();
            var entityProperties = entityType.GetProperties();

            //Check AssociationAttribute
            var associationProperties = entityProperties.Where(
               c => c.GetCustomAttributes(true).Any(
                   attrbute => attrbute.GetType().Name == "AssociationAttribute")
                   & c.PropertyType.IsGenericType);

            foreach (var associationProperty in associationProperties)
            {
                object propertyValue = associationProperty.GetValue(entity, null);

                IEnumerable enumerable = (IEnumerable)propertyValue;
                foreach (object o in enumerable)
                {
                    CascadingDeleteOnSubmit(context, o);
                }
            }

            try
            {
                context.GetTable(entity.GetType()).DeleteOnSubmit(entity);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
